package org.xbdframework.sample.sso.authserver.filter.customLogin;

import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static org.xbdframework.sample.sso.authserver.common.CommonConstants.HEADER_CLIENT;
import static org.xbdframework.sample.sso.authserver.common.CommonConstants.HEADER_TENANT_ID;


/**
 * @Author: Mr.Liu
 * @description: TODO
 * @date: 2023/8/8 9:39
 * @version: 1.0.0
 * @copyright: 中道新职坊
 */
public class CustomWebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, CustomWebAuthenticationDetails> {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public CustomWebAuthenticationDetails buildDetails(HttpServletRequest context) {
        String client = context.getHeader(HEADER_CLIENT);
        if (!StringUtils.hasText(client)) {
            client = context.getParameter(HEADER_CLIENT);
        }
        Long tenantId = null;
        String tenantIdStr = context.getHeader(HEADER_TENANT_ID);
        if (StringUtils.hasText(tenantIdStr)) {
            tenantId = Long.parseLong(tenantIdStr);
        } else {
            tenantIdStr = context.getParameter(HEADER_TENANT_ID);
            if (StringUtils.hasText(tenantIdStr)) {
                tenantId = Long.parseLong(tenantIdStr);
            }
        }
        return new CustomWebAuthenticationDetails(context, client, tenantId);
    }
}
